package manager

import (
	"fmt"
	"io/ioutil"
	"path"
	"plugin"
)

// PluginManager 插件管理器.
// Path 插件目录.
// Ext 插件后缀标识.
type PluginManager struct {
	Path string
	Ext  string
}

func NewPluginManager(path string, ext string) PluginManager {
	return PluginManager{
		Path: path,
		Ext:  ext,
	}
}

func loadPlugin(libraryPath string) (IPluginManagerMeta, error) {
	plug, err := plugin.Open(libraryPath)
	if err != nil {
		return nil, err
	}
	meta, err := plug.Lookup("PluginMeta")
	if err != nil {
		return nil, err
	}
	return meta.(IPluginManagerMeta), nil
}

func (m *PluginManager) LoadPlugins() ([]IPluginManagerMeta, error) {

	var pmm = []IPluginManagerMeta{}

	infos, err := ioutil.ReadDir(m.Path)
	if err != nil {
		return pmm, err
	}

	for _, info := range infos {
		if !info.IsDir() {
			if path.Ext(info.Name()) == m.Ext {
				pm, err := loadPlugin(path.Join(m.Path, info.Name()))
				if err != nil {
					fmt.Println(">>> 加载插件异常:", err.Error())
					continue
				}
				fmt.Printf(">>> 加载插件: %s\n", pm.PluginName())
				pmm = append(pmm, pm)
			}
		}
	}

	return pmm, nil
}
